<template>
  <div class="app-container">
    <div class="body-container mt0">
      <div class="operation-bar">
        <div class="bar-title">
          单位列表
        </div>
      </div>
      <el-table v-if="refreshTable" v-loading="loading" :data="deptList" stripe row-key="deptId"
        :default-expand-all="isExpandAll" :tree-props="{ children: 'children' }">
        <el-table-column prop="deptName" label="单位名称" min-width="150"></el-table-column>
        <el-table-column prop="leader" label="负责人" align="center" min-width="120"></el-table-column>
        <el-table-column prop="deptPic" label="图片" align="center" min-width="120">
          <template slot-scope="scope">
            <base-image-view :url="downloadUrl+scope.row.deptPic" v-if="scope.row.deptPic" cus_class="list-icon"></base-image-view>
          </template>
        </el-table-column>
        <el-table-column prop="deptAddress" label="地址" align="center" min-width="120"
          show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="orderNum" label="排序" min-width="100" align="center"></el-table-column> -->
        <el-table-column prop="label" label="状态" align="center" min-width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="170">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" min-width="120" class-name="small-padding fixed-width">
          <div class="table-option" slot-scope="scope" v-if="scope.row.roleId !== 1">
            <span @click="handleAdd(scope.row)" v-hasPermi="['system:dept:add']">新增</span>
            <span @click="handleUpdate(scope.row)" v-hasPermi="['system:dept:edit']">编辑</span>
            <span class="danger" @click="handleDelete(scope.row)" v-hasPermi="['system:dept:remove']"
              v-if="scope.row.parentId != 0">删除</span>
          </div>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增或编辑单位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级单位" prop="parentId">
          <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="请选择"
            class="input-w300" />
        </el-form-item>
        <el-form-item label="单位名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入" maxlength="20" clearable class="input-w300" />
        </el-form-item>
        <!-- <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="0" placeholder="请输入" maxlength="20"
            clearable />
        </el-form-item> -->
        <el-form-item label="负责人" prop="personnelId">
          <el-select v-model="form.personnelId"  placeholder="请选择" clearable filterable
            class="input-w300" >
            <el-option v-for="item in userList" :key="item.id" :label="item.personnelName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload ref="uploadImg" class="upload-demo" :limit="1" list-type="picture-card" :action="fileAction"
            :headers="fileHeaders" :file-list="fileList" :before-upload="beforeFileUpload" :on-success="handleFileSuccess"
            :on-remove="handleRemove">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="地址" prop="deptAddress">
          <el-input v-model="form.deptAddress" type="textarea" placeholder="请输入" maxlength="20" clearable
            class="input-w300" />
        </el-form-item>
        <el-form-item label="经度" prop="lng">
          <el-input v-model="form.lng" placeholder="请输入" maxlength="20" clearable class="input-w300" />
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入" maxlength="20" clearable class="input-w300" />
        </el-form-item>
        <el-form-item label="单位状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptTree, deptList, excludeDeptList, deptDetail, deptAdd, deptUpdate, deptDel } from "@/api/org";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";

export default {
  name: "Dept",
  dicts: ['sys_normal_disable'],
  components: { Treeselect },
  data () {
    return {
      userList: this.$store.state.user.userList,
      fileAction: process.env.VUE_APP_BASE_API + '/common/upload',
      fileHeaders: {
        Authorization: "Bearer " + getToken()
      },
      fileList: [],
      loading: true,
      showSearch: true,
      deptList: [],
      deptOptions: [],
      title: "",
      open: false,
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        leader: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级单位不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "单位名称不能为空", trigger: "blur" }
        ],
        // orderNum: [
        //   { required: true, message: "显示排序不能为空", trigger: "blur" }
        // ],
      }
    };
  },
  computed: {
    downloadUrl () {
      return process.env.VUE_APP_DOWNLOAD_URL
    },
  },
  created () {
    this.getList();
  },
  methods: {
    /** 查询单位列表 */
    getList () {
      this.loading = true;
      deptList(this.queryParams).then(response => {
        console.log(response.data)
        this.deptList = this.handleTree(response.data, "deptId")
        this.loading = false;
      });
    },
    /** 转换单位数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: 1,
        leader: undefined,
        personnelId:undefined,
        phone: undefined,
        email: undefined,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryParams = {
        deptName: undefined,
        leader: undefined,
        status: undefined
      }
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.fileList = []
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.deptId;
      }
      this.open = true;
      this.title = "新增单位";
      deptList().then(response => {
        this.fileList = []

        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 编辑按钮操作 */
    handleUpdate (row) {
      this.reset();
      this.fileList = []
      if(row.deptPic){
        this.fileList=[
          {
            name: '',
            url: this.downloadUrl + row.deptPic
          }
        ]
      }
      deptDetail(row.deptId).then(response => {
        this.form = response.data;
        console.log(this.form)
        this.form.parentId=parseInt(this.form.parentId)
        this.open = true;
        this.title = "编辑单位";
        excludeDeptList({
          deptId: row.deptId
        }).then(response => {
          this.deptOptions = this.handleTree(response.data, "deptId");
          if (this.deptOptions.length == 0) {
            const noResultsOptions = { deptId: this.form.parentId, deptName: this.form.parentName, children: [] };
            this.deptOptions.push(noResultsOptions);
          }
        });
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.fileList.length > 0) {
            this.form.deptPic = this.fileList.map(item => item.fileNameUrl).join(',')
          }else{
            this.form.deptPic=''
          }
          this.userList.map(item=>{
            if(item.id===this.form.personnelId){
              this.form.leader=item.personnelName
            }
          })
          if (this.form.deptId != undefined) {
            deptUpdate(this.form).then(response => {
              this.$modal.msgSuccess("编辑成功");
              this.open = false;
              this.fileList = []
              this.getList();
              this.$store.dispatch('GetDeptList').then(() => { })
            });
          } else {
            deptAdd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.fileList = []
              this.getList();
              this.$store.dispatch('GetDeptList').then(() => { })
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.$modal.confirm('是否确认删除数据？').then(function () {
        return deptDel(row.deptId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 文件上传前检查
    beforeFileUpload (file) {
      var FileExt = file.name.replace(/.+\./, "");
      const isLtM = file.size / 1024 / 1024 < 150;
      const fileTypeList = ['jpg', 'jpeg', 'png']
      let isFileType = fileTypeList.indexOf(FileExt.toLowerCase()) > -1
      if (!isFileType || !isLtM) {
        this.$message.error('请检查文件格式以及大小');
      }
      return isFileType && isLtM;
    },
    // 文件上传成功
    handleFileSuccess (res, file) {
      if (res.code === 200) {
        this.fileList.push({
          name: file.originalFilename,
          url: this.downloadUrl + res.fileName,
          fileNameUrl:res.fileName
        })
      }
    },
    // 文件删除
    handleRemove (file, fileList) {
      let index = fileList.indexOf(file);
      this.fileList.splice(index, 1)
    },
  }
};
</script>
